package com.example.utils;

import com.alibaba.dashscope.audio.asr.transcription.*;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

public class SpeechToTextUtils {
    public static void main(String[] args) {
        String text = getText("https://dashscope.oss-cn-beijing.aliyuncs.com/samples/audio/paraformer/hello_world_female2.wav");
        System.out.println(text);
    }

    public static String getText(String url) {
        // 创建转写请求参数，需要用真实apikey替换your-dashscope-api-key
        TranscriptionParam param =
                TranscriptionParam.builder()
                        .apiKey("sk-6dc42d332c60438d820dc5c303a3c1ff")
                        .model("paraformer-v2")
                        .fileUrls(
                                Collections.singletonList(
                                        url))
                        .parameter("language_hints", new String[]{"zh", "en"})
                        .build();
        try {
            Transcription transcription = new Transcription();
            // 提交转写请求
            TranscriptionResult result = transcription.asyncCall(param);
            // 打印TaskId
            System.out.println("TaskId: " + result.getTaskId());
            // 等待转写完成
            result =
                    transcription.wait(
                            TranscriptionQueryParam.FromTranscriptionParam(param, result.getTaskId()));
            // 获取转写结果
            List<TranscriptionTaskResult> taskResultList = result.getResults();
            if (taskResultList != null && taskResultList.size() > 0) {
                TranscriptionTaskResult taskResult = taskResultList.get(0);
                // 获取转写结果的url
                String transcriptionUrl = taskResult.getTranscriptionUrl();
                // 通过Http获取url内对应的结果
                HttpURLConnection connection =
                        (HttpURLConnection) new URL(transcriptionUrl).openConnection();
                connection.setRequestMethod("GET");
                connection.connect();
                BufferedReader reader =
                        new BufferedReader(new InputStreamReader(connection.getInputStream()));
                // 格式化输出json结果
                Gson gson = new GsonBuilder().setPrettyPrinting().create();
                String s = gson.toJson(gson.fromJson(reader, JsonObject.class));
                JSONObject jsonObject = JSONObject.parseObject(s);
                JSONArray transcripts = jsonObject.getJSONArray("transcripts");
                Object o = transcripts.get(0);
                if (Objects.nonNull(o)) {
                    String s1 = o.toString();
                    JSONObject jsonObject1 = JSONObject.parseObject(s1);
                    Object text = jsonObject1.get("text");
                    return text.toString();
                };
            }
        } catch (Exception e) {
            System.out.println("error: " + e);
        }
        System.exit(0);
        return null;
    }

    ;
}
